import { useState, useEffect, createContext, useContext } from 'react';
import { getUserVotes } from '../services/api';
import type { Vote } from '../types';

type VotesMap = { [postId: number]: number };

interface VotesContextType {
    votes: VotesMap;
    refetchVotes: () => void;
}

const VotesContext = createContext<VotesContextType | undefined>(undefined);

export const VotesProvider = ({ children }: { children: React.ReactNode }) => {
    const [votes, setVotes] = useState<VotesMap>({});

    const fetchVotes = async () => {
        // Only fetch if a token exists
        const token = localStorage.getItem('token');
        if (token) {
            const userVotes: Vote[] = await getUserVotes();
            if (Array.isArray(userVotes)) {
                const votesMap = userVotes.reduce((acc, vote) => {
                    // Defensive check to make sure vote object is valid
                    if (vote && typeof vote.post_id !== 'undefined' && typeof vote.vote_type !== 'undefined') {
                        acc[vote.post_id] = vote.vote_type;
                    }
                    return acc;
                }, {} as VotesMap);
                setVotes(votesMap);
            }
        } else {
            // If no token, ensure votes are an empty object
            setVotes({});
        }
    };

    useEffect(() => {
        fetchVotes();
    }, []); // Run once on initial mount

    const contextValue = {
        votes,
        refetchVotes: fetchVotes,
    };

    return (
        <VotesContext.Provider value={contextValue}>
            {children}
        </VotesContext.Provider>
    );
};

export const useVotes = () => {
    const context = useContext(VotesContext);
    if (context === undefined) {
        throw new Error('useVotes must be used within a VotesProvider');
    }
    return context;
};
